"use client";
import React, { useEffect, useRef, useState } from "react";
import useCaptionsStore, {
  ConversationGroup,
  Message,
} from "@/app/store/captions";
import "./index.scss";

interface RollCaptionsProps {}

// 打印机打字效果
const TypewriterText: React.FC<{
  text: string;
  isStreaming?: boolean;
  speed?: number;
}> = ({ text, isStreaming = false, speed = 50 }) => {
  const [displayText, setDisplayText] = useState("");
  const [isTyping, setIsTyping] = useState(false);
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  // 清理定时器
  const clearTimer = () => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
  };

  // 打字机效果
  useEffect(() => {
    clearTimer();
    if (!isStreaming) {
      // 如果不是流式状态，直接显示完整文本
      setDisplayText(text);
      setIsTyping(false);
      return;
    }

    // 流式状态下的打字机效果
    if (displayText.length < text.length) {
      setIsTyping(true);
      timerRef.current = setTimeout(() => {
        setDisplayText(text.slice(0, displayText.length + 1));
      }, speed);
    } else {
      setIsTyping(false);
    }

    return clearTimer;
  }, [text, displayText.length, isStreaming, speed]);

  // 当文本变化时重置显示文本（只在流式状态下）
  useEffect(() => {
    if (isStreaming && text.length < displayText.length) {
      setDisplayText("");
    }
  }, [text, isStreaming, displayText.length]);

  // 组件卸载时清理定时器
  useEffect(() => {
    return clearTimer;
  }, []);

  // const shouldShowCursor = isStreaming && isTyping;

  return (
    <span>
      {displayText}
      {/* {shouldShowCursor && <span className="typewriter-cursor">|</span>} */}
    </span>
  );
};

// 对话框
const RollCaptions: React.FC<RollCaptionsProps> = ({}) => {
  const { conversations, currentConversation } = useCaptionsStore();
  const scrollContainerRef = useRef<HTMLDivElement>(null);

  // 自动滚动到底部
  useEffect(() => {
    const scrollToBottom = () => {
      if (scrollContainerRef.current) {
        const container = scrollContainerRef.current;
        // 使用requestAnimationFrame确保DOM更新完成后再滚动
        requestAnimationFrame(() => {
          container.scrollTo({
            top: container.scrollHeight,
            behavior: "smooth",
          });
        });
      }
    };

    // 添加小延迟确保内容渲染完成
    const timer = setTimeout(scrollToBottom, 100);
    return () => clearTimeout(timer);
  }, [conversations, currentConversation]);
  // 渲染消息
  const renderMessage = (message: Message, isCurrentConv = false) => {
    // 添加防护确保消息对象有效
    if (!message || !message.id || !message.type) {
      return null;
    }
    return (
      <div
        key={message.id}
        className={`message ${message.type} ${
          isCurrentConv ? "current" : "history"
        }`}
      >
        <div className="message-bubble">
          <div className="message-content">
            {message.type === "ai" ? (
              <TypewriterText
                text={message.content || ""}
                isStreaming={
                  isCurrentConv ? message.isStreaming || false : false
                }
                speed={50}
              />
            ) : (
              message.content || ""
            )}
            {message.isStreaming &&
              message.type === "ai" &&
              !message.content && (
                <span className="streaming-indicator">
                  <span className="dot"></span>
                  <span className="dot"></span>
                  <span className="dot"></span>
                </span>
              )}
          </div>
          <div className="message-time">
            {new Date(message.timestamp).toLocaleTimeString("zh-CN", {
              hour: "2-digit",
              minute: "2-digit",
            })}
          </div>
        </div>
      </div>
    );
  };

  const renderConversation = (
    conversation: ConversationGroup,
    isHistory = true
  ) => (
    <div
      key={conversation.id}
      className={`conversation-group ${isHistory ? "history" : "current"}`}
    >
      {renderMessage(conversation.userMessage, !isHistory)}
      {conversation.aiMessage &&
        renderMessage(conversation.aiMessage, !isHistory)}
    </div>
  );

  // 只有当有对话内容时才显示字幕组件
  const hasContent = conversations.length > 0 || currentConversation;

  if (!hasContent) {
    return null;
  }

  return (
    <div className="roll-captions">
      <div className="captions-container" ref={scrollContainerRef}>
        {/* 历史对话 */}
        <div className="conversations-history">
          {conversations.map((conversation) =>
            renderConversation(conversation, true)
          )}
        </div>

        {/* 当前对话 */}
        {currentConversation && (
          <div className="current-conversation">
            {renderConversation(currentConversation, false)}
          </div>
        )}
      </div>
    </div>
  );
};

export default RollCaptions;
